﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Icinetic.FeedCategorySample.Entities;
using Icinetic.FeedCategorySample.Services;
using Icinetic.FeedCategorySample.Services.Providers;
using Icinetic.FeedCategorySample.Services.Repositories;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage;
using Windows.Storage.Streams;

namespace Icinetic.FeedCategorySample.ViewModel
{
    public class ArticlePageViewModel
    {
        private RssItem _item = new RssItem();
        public virtual RssItem Item
        {
            get { return this._item; }
            set { this._item = value; }
        }

        public ArticlePageViewModel() 
        {
            
        }

        public void LoadFeedItem(RssItem rssItem) 
        {
            ReadSaveChanges(rssItem);
            Item = rssItem;
        }

        public async void FillShareInfo(DataRequest request)
        {
            string dataPackageTitle = Item.TitleAll;
            string dataPackageText = Item.Content;
            Uri dataPackageUri = new Uri(Item.Link);

            DataPackage requestData = request.Data;
            requestData.Properties.Title = dataPackageTitle;
            requestData.SetText(dataPackageText);
            requestData.SetUri(dataPackageUri);

            if (!string.IsNullOrEmpty(Item.Image))
            {
                string imageName = string.Empty;
                imageName = await TemporalImageStorageProvider.StoreImage(Item.Image);
                IStorageFolder cacheFolder = await TemporalImageStorageProvider.GetTemporalStorageFolder();
                IStorageFile file = await cacheFolder.GetFileAsync(imageName);
                List<IStorageItem> imageItems = new List<IStorageItem>();
                imageItems.Add(file);
                requestData.SetStorageItems(imageItems);

                RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(file);
                requestData.Properties.Thumbnail = imageStreamRef;
                requestData.SetBitmap(imageStreamRef);
            }
        }

        private void ReadSaveChanges(RssItem rssItem)
        {
            RssItemRepository rssItemService = new RssItemRepository();
            rssItem.IsRead = true;
            rssItemService.Change(rssItem);
        }
    }
}
